-------------------------------------------------------------------------------
-- RTSAI - Real-Time Strategy engine for AI research
-- Copyright(C) 2006 DIMAp-UFRN, licensed under LGPL
--
-- RTSAI full capture-the-flag state machine example
-------------------------------------------------------------------------------

State {
    name = "cd_starting",  -- obligatory state
    act = function ( self )
        self.unit : broadcastMessage ( rtsai.Message.INFORM, "going to flag" )
        action.change_state.state = cd_seekingFlag : new()
        return action.change_state
    end
}


State {
    name = "cd_wakingUp", -- obligatory state
    act = function ( self )
        action.change_state.state = cd_seekingFlag : new()
        return action.change_state
    end
}


State {
    name = "cd_seekingFlag",

    act = function ( self )
        local player = self.unit : get_player()
        action.move.steer = self.unit : steerForSeek ( player.flag : position() )
        return action.move
    end,

    on_message = function ( self, messages )
        for i = 0, messages:size() - 1 do
            local msg = messages[i]
            if msg:get_performative() == rtsai.Message.INFORM and msg:get_content() == "going to flag" then
                self.unit : answer ( msg, rtsai.Message.INFORM, "i'm already going there" )
            end
        end
    end,

    on_unit_frozen = function ( self, event )
        if event.player == self.unit:get_player() then
            self.unit : broadcastMessage ( rtsai.Message.INFORM, "going to help unit" )
            return cd_helpingFrozenUnit : new ( { frozen = event.unit } )
        end
    end
}


State {
    name = "cd_helpingFrozenUnit",

    act = function ( self )
        if self.frozen then
            action.move.steer = self.unit : steerForSeek ( self.frozen : position() )
            return action.move
        end
    end,

    on_unit_wakeup = function ( self, event )
        if event.unit == self.frozen then
            return cd_seekingFlag : new()
        end
    end
}
